package com.example.myys.viewModel.mhModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myys.data.entity.ChapterBean
import com.example.myys.data.repository.ComicRepository
import com.example.myys.ui.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch


class MhNrViewModel:ViewModel() {
    val comicRepository = ComicRepository()
    //章节列表
    private val _zjlbState: MutableStateFlow<Resource<List<ChapterBean>>>
            = MutableStateFlow(value = Resource.Loading())

    val zjlbState: StateFlow<Resource<List<ChapterBean>>>
        get() = _zjlbState
    //内容
    private val _nrState: MutableStateFlow<Resource<String>>
            = MutableStateFlow(value = Resource.Loading())

    val nrState: StateFlow<Resource<String>>
        get() = _nrState

    fun getComicChapterList(dataUrl: String, dataId: Int) {
        _zjlbState.value=Resource.Loading()
        viewModelScope.launch(Dispatchers.IO) {
            val xsChapterList = comicRepository.getComicChapterList(dataUrl, dataId)
            if(xsChapterList!=null){
                _zjlbState.value=Resource.Success(xsChapterList)
                if(xsChapterList.isNotEmpty()){
                    getChapterContent(xsChapterList.get(0).url,xsChapterList.get(0).id,xsChapterList.get(0).dataBeanId)
                }
            }else{
                _zjlbState.value=Resource.Error()
            }
        }
    }
    fun getChapterContent(chapterUrl:String,id:Int,dataId: Int){
        _nrState.value=Resource.Loading()
        viewModelScope.launch (Dispatchers.IO){
            val cont = comicRepository.getComicContent(chapterUrl, id, dataId)
            if(cont==null){
                _nrState.value=Resource.Error()
            }else{
                _nrState.value=Resource.Success(cont)
            }
        }
    }

    init {

    }

}